package com.security.config.security;

import com.security.Filter.MobileCaptchaFilter.MobileCapchaAuthenticationFilter;
import com.security.Filter.MobileCaptchaFilter.MobileCapchaAuthenticationProvider;
import com.security.Filter.MobileCaptchaFilter.MobileCapchaCodeFilter;
import com.security.Filter.SecurityFilter.*;
import com.security.system.service.SysUserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class MobileCapchaSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    SecuritySuccessHandler successHandler;

    @Resource
    SecurityFailureHandler failureHandler;

    @Resource
    SysUserService userService;

    @Resource
    MobileCapchaCodeFilter captchaCodeFilter;

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        MobileCapchaAuthenticationFilter mobileCapchaFilter = new MobileCapchaAuthenticationFilter();
        mobileCapchaFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        mobileCapchaFilter.setAuthenticationSuccessHandler(successHandler);
        mobileCapchaFilter.setAuthenticationFailureHandler(failureHandler);

        MobileCapchaAuthenticationProvider provider = new MobileCapchaAuthenticationProvider();
        provider.setUserDetailsService(userService);

        builder.addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class);
        builder.authenticationProvider(provider)
                .addFilterAfter(mobileCapchaFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
